using System;
using System.Collections.Specialized;
using Exceptions;

namespace Param
{
    public class Args
    {
        private StringDictionary Named;
        private StringCollection Unnamed;

        public Args()
        {
            Named = new StringDictionary();
            Unnamed = new StringCollection();
        }

        public string GetValue(string key)
        {
            key = key.ToUpper();
            if (Named.ContainsKey(key)) return Named[key];
            else if (Unnamed.Count > 0)
            {
                string value = Unnamed[0];
                AddToNamed(key, value);
                Unnamed.RemoveAt(0);
                return value;
            }
            else return null;
        }

        public void AddToNamed(string key, string value)
        {
            if (!Named.ContainsKey(key)) Named.Add(key, value);
        }
        public void AddToUnnamed(string value) { Unnamed.Add(value); }

        public void Parse(string[] args)
        {
            BaseArg argObject = CreateArg();
            BaseArg nextArgObject;
            foreach (string arg in args)
            {
                nextArgObject = CreateArg(arg);
                argObject.Add(nextArgObject);
                argObject = nextArgObject.Updated;
            }
            argObject.Add(CreateArg());
        }

        public BaseArg CreateArg(string arg)
        {
            return (IsKeyString(arg)) ? (BaseArg)(new ArgKey(this, arg)) : (BaseArg)(new ArgValue(this, arg));
        }

        public BaseArg CreateArg() { return new ArgNone(this); }

        public static bool IsKeyString(string str) { return (str.Length > 0) && (str[0] == '-'); }
    }
}